﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using System.IO;
using CNotebook;
using CNotebook.Sales;
using NotebookS2.Sales.Dialogs;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class SalesInvoice : RibbonForm
    {
        public SalesInvoice()
        {
            InitializeComponent();
        }

        public bool UpdateDataOnStatus { get; set; }
        public Keys UsedKey = Keys.None;
        public int ObjectType { get { return 5; } }

        #region Properties
        public bool IsExportedFromDR { get; set; }
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public string DefaultWarehouse { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public DataTable DeliveryLineItems { get; set; }
        public DataTable AccountingEntries { get; set; }
        public double WithHoldingTaxRate { get; set; }

        public string DefaultPriceList { get; set; }
        
        public string VATCode { get; set; }
        public string VATRate { get; set; }
        public bool IsInclusive { get; set; }
        #endregion

        #region Initialization

        public void GetBusinessPartnerDefaults(string sCardCode)
        {
            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();

            this.DefaultPriceList = oBPManager.GetPriceListCode(sCardCode);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(sCardCode);

            txtPaymentTerms.Text = oBPManager.GetPaymentTerm(sCardCode);
            txtDivision.Text = oBPManager.GetDivision(sCardCode);
            oBPManager.Close();
            #endregion


            //dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

            #endregion


        }

        public string GetIsAutoDRConfig()
        {
            string sPath = System.Windows.Forms.Application.StartupPath.ToString() + "\\config.conf";
            string _OUTPUT_STRING = "";

            if (File.Exists(sPath) == true)
            {
                StreamReader sr = File.OpenText(sPath);
                string input;

                do
                {
                    input = sr.ReadLine();
                    if (input != null)
                    {

                        if (input.StartsWith("AutoDR") == true)
                        {
                            int iStart = input.IndexOf("=");
                            _OUTPUT_STRING = input.Substring(iStart + 1);

                            break;
                        }

                    }
                } while (input != null);

            }
            return _OUTPUT_STRING;

        }

        private static DataTable GetTable()
        {
            DataTable table = new DataTable();

            table.Columns.Add("ItemCode", typeof(string));
            table.Columns.Add("ItemDesc", typeof(string));
            table.Columns.Add("UoM", typeof(string));
            table.Columns.Add("Qty", typeof(double));
            table.Columns.Add("CQty", typeof(double));
            table.Columns.Add("LotNumber", typeof(string));
            table.Columns.Add("PriceListCode", typeof(string));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("UnitCost", typeof(double));
            table.Columns.Add("IsFree", typeof(bool));
            table.Columns.Add("DiscPrcnt", typeof(double));
            table.Columns.Add("Discount", typeof(double));
            table.Columns.Add("TotalLineDisc", typeof(double));
            table.Columns.Add("Amount", typeof(double));
            table.Columns.Add("ItemGuID", typeof(string));
            
            return table;

        }

        private static DataTable GetGLAcctStructure()
        {
            DataTable table = new DataTable();

            table.Columns.Add("DocNum", typeof(string));
            table.Columns.Add("AcctCode", typeof(string));
            table.Columns.Add("AcctName", typeof(string));
            table.Columns.Add("Particulars", typeof(string));
            table.Columns.Add("DebitAmt", typeof(double));
            table.Columns.Add("CreditAmt", typeof(double));

            return table;
        }

        void InitializeSeries()
        {
            string ObjectType = this.ObjectType.ToString();
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            lblValidUntilDeliveryDate.Text = "Due Date:";
            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();   
        }
        
        #endregion

        #region Functions
        void RemoveBlankLastGLAccounts()
        {
            gridViewInvAcctEntries.MoveLast();
            try
            {
                string _AcctCode = "";


                if (gridViewInvAcctEntries.GetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"]) != null)
                {
                    _AcctCode = gridViewInvAcctEntries.GetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"]).ToString();
                }
                else
                {
                    _AcctCode = "";
                }

                if (_AcctCode.Trim() == "")
                {
                    gridViewInvAcctEntries.DeleteRow(gridViewInvAcctEntries.FocusedRowHandle);
                }
            }
            catch { }

        }

        private void BindLotNumber(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            StockManager oManager = new StockManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            if (cboLocation.EditValue == null)
            {
                MessageBox.Show("Please select warehouse!!!", "Warehouse", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cboLocation.Focus();
                cboLocation.ShowPopup();
                return;
            }

            DataTable _table = oManager.GetLotNumbers(sItemCode, cboLocation.EditValue.ToString());


            oManager.Close();

            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["LotNumber"].ToString());
            }



        }

        public string GetDiscountMethod()
        {
            string sPath = System.Windows.Forms.Application.StartupPath.ToString() + "\\config.conf";
            string _OUTPUT_STRING = "";


            if (File.Exists(sPath) == true)
            {


                StreamReader sr = File.OpenText(sPath);
                string input;

                do
                {
                    input = sr.ReadLine();
                    if (input != null)
                    {

                        if (input.StartsWith("DiscountMethod") == true)
                        {
                            int iStart = input.IndexOf("=");
                            _OUTPUT_STRING = input.Substring(iStart + 1);

                            break;
                        }

                    }
                } while (input != null);


            }
            return _OUTPUT_STRING;

        }
        public void CopyDRToInvoice(string _DRDocumentNumber)
        {
            DateTime _NOW = System.DateTime.Now;

            InitializeSeries();             // Initialize Series
            this.IsExportedFromDR = true;   // Indicator that it was imported from Sales Order
            
            dtPostDate.EditValue        = _NOW;
            dtDeliveryDate.EditValue    = _NOW;
            dtDocDate.EditValue         = _NOW;

            BindWarehouse();                        // Binding the Combo Box Warehouse/Location
            BindSalesMan();                         // Binding Sales Man/Accounts
            BindCardDocument();
            
            txtPaymentTerms.Text = "0";
            
            if (this.IsMultipleWarehouse == false)  // Enable the Selection of Combo Box if the Users Allowed to Select Multiple Warehouse
            {
                cboLocation.Enabled = false;
            }            

            if (txtReference.Text != "")            // Reference Sales Order
            {
                return;
            }

            #region Intializing Issued Items Table and Line Items
          
            if (this.DeliveryLineItems == null)
            {
                this.DeliveryLineItems = GetTable();
            }

            gridControlSI.DataSource = this.DeliveryLineItems; // Line Items Data Table Binding in Grid
            gridControlSI.Refresh();

            if (gridViewSI.DataRowCount <= 0)
            {
                gridViewSI.AddNewRow();
            }

            if (this.AccountingEntries == null)
            {
                this.AccountingEntries = GetGLAcctStructure();
            }

            gridInvAcctEntries.DataSource = this.AccountingEntries;
            gridInvAcctEntries.Refresh();

            if (gridViewInvAcctEntries.DataRowCount <= 0)
            {
                gridViewInvAcctEntries.AddNewRow();
            }

            #endregion

            DeliveryManager oManager = new DeliveryManager();

            #region Retrieving the Delivered Transaction - Header
            

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            txtReference.Text = _DRDocumentNumber;
            
            DataRow oHeaderRowDR = oManager.GetDelivery(_DRDocumentNumber);

            cboLocation.EditValue = oHeaderRowDR["Location"].ToString();
            txtStoreCode.Text = oHeaderRowDR["StoreCode"].ToString();
            txtCardCode.Text = oHeaderRowDR["CardCode"].ToString();
            txtCardName.Text = oHeaderRowDR["CardName"].ToString();
            txtBillTo.Text = oHeaderRowDR["BillTo"].ToString();
            txtShipTo.Text = oHeaderRowDR["ShipTo"].ToString();
            txtContactPerson.Text = oHeaderRowDR["ContactPerson"].ToString();
            cboSalesman.EditValue = oHeaderRowDR["SalesMan"].ToString();
            try
            {
                txtDisc1.Text = oHeaderRowDR["Discount1"].ToString() ;
                txtDisc2.Text = oHeaderRowDR["Discount2"].ToString() ;
                txtDisc3.Text = oHeaderRowDR["Discount3"].ToString() ;
                txtDisc4.Text = oHeaderRowDR["Discount4"].ToString();
            }
            catch
            {
            }
            this.VATCode = oHeaderRowDR["VATCode"].ToString();
            txtPaymentTerms.Text = oHeaderRowDR["PaymentTerms"].ToString();
            txtCustRefPO.Text = oHeaderRowDR["Reference"].ToString();
            #endregion

            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();
            
            this.DefaultPriceList = oBPManager.GetPriceListCode(txtCardCode.Text);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(txtCardCode.Text);

            txtPaymentTerms.Text = oBPManager.GetPaymentTerm(txtCardCode.Text); 
            txtDivision.Text = oBPManager.GetDivision(txtCardCode.Text);
            cboDocument.EditValue = oBPManager.GetDocument(txtCardCode.Text);
            oBPManager.Close();
            #endregion

            
            //dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;
            

            #endregion


            #region Importing the Sales Delivery Line Item to Delivery Line Items
            // Getting the Posted Order
            DataTable _TABLE_POSTED_ORDER = oManager.GetDeliveryLineItems(txtReference.Text);

            _TABLE_POSTED_ORDER.AcceptChanges();

            // Inserting the Line Items from Sales Order to Delivery Line Items
            if (_TABLE_POSTED_ORDER.Rows.Count > 0) 
            {
                this.DeliveryLineItems = _TABLE_POSTED_ORDER;

                gridControlSI.DataSource = this.DeliveryLineItems;
                gridControlSI.Refresh();
                oManager.Close();
            }

            #endregion

            
            // Set up the Due Date based on the Terms
            DateTime _PostDate = (DateTime)dtPostDate.EditValue;

            dtDeliveryDate.EditValue = _PostDate.AddDays(Convert.ToInt16(txtPaymentTerms.Text));
            
            gridControlSI.DataSource = this.DeliveryLineItems;
            gridControlSI.Refresh();
            
            ComputeTotal();
            ApplyVolumeDiscount();

        }

        public void PrintPreview()
        {
            NotebookS2.Sales.Layouts.CHOOSE_LAYOUT oForm = new Sales.Layouts.CHOOSE_LAYOUT();

            oForm.ConnectionString = this.ConnectionString;
            oForm.DocumentNumber = txtDocumentNumber.Text;
            oForm.ShowDialog();

            //PRNT_INV oPrint = new PRNT_INV();

            //oPrint.ConnectionString = this.ConnectionString;
            //oPrint.DocumentNumber = txtDocumentNumber.Text;

            //oPrint.WindowState = FormWindowState.Maximized;
            //oPrint.ShowDialog();
        }

        void DisableControls()
        {
            cboLocation.Enabled = false;
            txtCardCode.Enabled = false;
            txtStoreCode.Enabled = false;
            txtCardName.Enabled = false;
            txtContactPerson.Enabled = false;
            txtReference.Enabled = false;
            txtCustRefPO.Enabled = false;
            txtBillTo.Enabled = false;
            txtShipTo.Enabled = false;
            txtDocumentNumber.Enabled = false;
            dtPostDate.Enabled = false;
            dtDeliveryDate.Enabled = false;
            dtDocDate.Enabled = false;
            cboDocument.Enabled = false;
            cboSalesman.Enabled = false;
            txtRemarks.Enabled = false;
            txtGrossAmount.Enabled = false;
            txtTotalLineDiscount.Enabled = false;
            txtDisc1.Enabled = false;
            txtDisc2.Enabled = false;
            txtDisc3.Enabled = false;
            txtDisc4.Enabled = false;
            txtTotalDiscount.Enabled = false;
            txtVAT.Enabled = false;
            txtNetAmt.Enabled = false;
            txtWithHoldingTax.Enabled = false;
            txtDivision.Enabled = false;
            txtRefDoc.Enabled = false;
            btnAdd.Enabled = false;
            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridViewSI.Columns)
            {
                oColumn.OptionsColumn.AllowEdit = false;
            }

        }

        void EnableControls()
        {
            if (this.IsMultipleWarehouse == true)
            {
                cboLocation.Enabled = true;
            }
            txtStoreCode.Enabled = true;
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            txtContactPerson.Enabled = true;
            txtReference.Enabled = true;
            txtCustRefPO.Enabled = true;
            txtBillTo.Enabled = true;
            txtShipTo.Enabled = true;
            txtDocumentNumber.Enabled = true;
            dtPostDate.Enabled = true;
            dtDeliveryDate.Enabled = true;
            dtDocDate.Enabled = true;

            txtRefDoc.Enabled = true;
            cboSalesman.Enabled = true;
            cboDocument.Enabled = true;
            txtRemarks.Enabled = true;
            txtGrossAmount.Enabled = true;
            txtTotalLineDiscount.Enabled = true;
            txtDisc1.Enabled = true;
            txtDisc2.Enabled = true;
            txtDisc3.Enabled = true;
            txtDisc4.Enabled = true;
            txtTotalDiscount.Enabled = true;
            txtVAT.Enabled = true;
            txtNetAmt.Enabled = true;
            txtWithHoldingTax.Enabled = false;
            btnAdd.Enabled = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridViewSI.Columns)
            {
                if (oColumn.Name == "Code" || oColumn.Name == "SrvdQty")
                {
                    oColumn.OptionsColumn.AllowEdit = true;
                }
            }

        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = this.ObjectType.ToString();

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        private void ComputeTotal()
        {
            try
            {
                double _GrossAmount = 0;
                double _NetAmount = 0;
                double _LineDiscount = 0;

                foreach (DataRow oRow in this.DeliveryLineItems.Rows)
                {

                    if (oRow["Amount"] != DBNull.Value)
                    {
                        bool IsFree = false;
                        if (oRow["IsFree"] != DBNull.Value)
                        {
                            IsFree = Convert.ToBoolean(oRow["IsFree"]);
                        }
                        else
                        {
                            IsFree = false;
                        }


                        if (IsFree == false)
                        {
                            _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                            _NetAmount = _NetAmount + (Convert.ToDouble(oRow["Amount"]));
                            if (oRow["TotalLineDisc"] == DBNull.Value)
                            {
                                oRow["TotalLineDisc"] = 0;
                            }
                            _LineDiscount = _LineDiscount + (Convert.ToDouble(oRow["TotalLineDisc"]));
                        }
                    }
                }

                double _VAT = 0;

                double _VolumeDiscount = Convert.ToDouble(txtTotalDiscount.Text);


                if (this.VATCode == "VAT Inclusive")
                {
                    if (this.IsInclusive == true)
                    {

                        _VAT = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate));
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();

                        //txtWithHoldingTax.Text = Convert.ToString(((_NetAmount / Convert.ToDouble(this.VATRate)) * (this.WithHoldingTaxRate / 100)).ToString("##.00"));

                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }

                }

                if (this.VATCode == "VAT Exclusive")
                {
                    if (this.IsInclusive == false)
                    {
                        _VAT = _NetAmount * Convert.ToDouble(this.VATRate);
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();

                        //txtWithHoldingTax.Text = Convert.ToString((_NetAmount * (this.WithHoldingTaxRate / 100)).ToString("##.00"));
                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }
                }

                txtTotalLineDiscount.Text = _LineDiscount.ToString("#,###.00");
                txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");

                txtNetAmt.Text = _NetAmount.ToString("#,###.00");
                txtWithHoldingTax.Text = ((_NetAmount - _VolumeDiscount) * (this.WithHoldingTaxRate / 100)).ToString();



            }
            catch
            {
            }

        }

        private void ApplyVolumeDiscount()
        {

            double _GrossAmount = 0;
            double _NetAmount = 0;
            double _TotalLineDiscount = 0;
            double _VatAmount = 0;

            foreach (DataRow oRow in this.DeliveryLineItems.Rows)
            {

                if (oRow.RowState != DataRowState.Deleted)
                {
                    if (oRow["CQty"] == DBNull.Value)
                    {
                        oRow["CQty"] = 0;
                    }

                    if (oRow["Qty"] == DBNull.Value)
                    {
                        oRow["Qty"] = 0;
                    }
                    if (oRow["UnitPrice"] == DBNull.Value)
                    {
                        oRow["UnitPrice"] = 0;
                    }
                    if (oRow["TotalLineDisc"] == DBNull.Value)
                    {
                        oRow["TotalLineDisc"] = 0;
                    }
                    if (oRow["IsFree"] == DBNull.Value)
                    {
                        oRow["IsFree"] = false;
                    }
                    bool IsFree = Convert.ToBoolean(oRow["IsFree"]);

                    if (IsFree != true)
                    {
                        _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                        _TotalLineDiscount = _TotalLineDiscount + Convert.ToDouble(oRow["TotalLineDisc"]);
                    }
                }

            }

            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");


            string sDiscount1 = txtDisc1.Text.Replace("%", "");
            string sDiscount2 = txtDisc2.Text.Replace("%", "");
            string sDiscount3 = txtDisc3.Text.Replace("%", "");
            string sDiscount4 = txtDisc4.Text.Replace("%", "");


            double _disc1 = 0;
            double _disc2 = 0;
            double _disc3 = 0;
            double _disc4 = 0;


            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);

            double _TotalDiscount = 0;

            double _discount1 = 0;
            double _discount2 = 0;
            double _discount3 = 0;
            double _discount4 = 0;

            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);


            if (txtDisc4.Text == "")
            {
                _disc4 = 0;
            }
            else
            {
                _disc4 = Convert.ToDouble(sDiscount4);
            }

            if (_disc1 > 0)
            {
                _discount1 = (_GrossAmount - _TotalLineDiscount) * (_disc1 / 100);

                _TotalDiscount = (_GrossAmount - _TotalLineDiscount) - _discount1;
            }
            if (_disc2 > 0)
            {
                _discount2 = (_TotalDiscount * (_disc2 / 100));
                _TotalDiscount = _TotalDiscount - _discount2;

            }
            if (_disc3 > 0)
            {
                _discount3 = (_TotalDiscount * (_disc3 / 100));
                _TotalDiscount = _TotalDiscount - _discount3;
            }

            if (_disc4 > 0)
            {
                _discount4 = (_TotalDiscount * (_disc4 / 100));
                _TotalDiscount = _TotalDiscount - _discount4;
            }

            _TotalDiscount = (_discount1 + _discount2 + _discount3 + _discount4);
            txtTotalDiscount.Text = _TotalDiscount.ToString("#,###.00");



            txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");
            txtTotalLineDiscount.Text = _TotalLineDiscount.ToString("#,###.00");

            _NetAmount = (_GrossAmount - _TotalDiscount) - _TotalLineDiscount;


            string _DISCOUNT_METHOD = GetDiscountMethod();
            if (this.VATCode != "NON-VAT")
            {
                if (_DISCOUNT_METHOD == "After")
                {
                    if (this.VATCode == "VAT Inclusive")
                    {
                        _VatAmount = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate));
                    }
                    else if (this.VATCode == "VAT Exclusive")
                    {
                        _VatAmount = _NetAmount * Convert.ToDouble(this.VATRate);
                        _NetAmount = _NetAmount + _VatAmount;
                    }
                }
                else
                {
                    if (this.VATCode == "VAT Inclusive")
                    {
                        _VatAmount = _GrossAmount - (_GrossAmount / Convert.ToDouble(this.VATRate));
                    }
                    else if (this.VATCode == "VAT Exclusive")
                    {
                        _VatAmount = _GrossAmount * Convert.ToDouble(this.VATRate);
                        _NetAmount = ((_GrossAmount + _VatAmount) - (_TotalDiscount - _TotalDiscount));
                    }
                }
            }




            txtVAT.Text = _VatAmount.ToString("#,###.00");
            txtNetAmt.Text = _NetAmount.ToString("#,###.00");
            txtWithHoldingTax.Text = (_NetAmount * (this.WithHoldingTaxRate / 100)).ToString();

            #region Returning Percent Sign
            if (_disc1 > 0)
            {
                txtDisc1.Text = _disc1.ToString("#.00") + "%";
            }
            else
            {
                txtDisc1.Text = "0%";
            }
            if (_disc2 > 0)
            {
                txtDisc2.Text = _disc2.ToString("#.00") + "%";
            }
            else
            {
                txtDisc2.Text = "0%";
            }
            if (_disc3 > 0)
            {
                txtDisc3.Text = _disc3.ToString("#.00") + "%";
            }
            else
            {
                txtDisc3.Text = "0%";
            }

            if (_disc4 > 0)
            {
                txtDisc4.Text = _disc4.ToString("#.00") + "%";
            }
            else
            {
                txtDisc4.Text = "0%";
            }
            #endregion


        }
        void BindCardDocument()
        {
            CardDocumentManager oManager = new CardDocumentManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable dtDocuments = oManager.GetCardDocument();

            oManager.Close();

            cboDocument.Properties.Items.Clear();

            foreach (DataRow row in dtDocuments.Rows)
            {
                cboDocument.Properties.Items.Add(row["Code"]);
            }
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();
           


            cboLocation.Visible = false;
            cboLocation.Properties.DataSource = oTable;
            cboLocation.Properties.DisplayMember = "Dscription";
            cboLocation.Properties.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboLocation.Properties.Columns.Add(col);
            cboLocation.Properties.ShowHeader = false;
            cboLocation.Visible = true;
            oManager.Close();
        }

        void BindSalesMan()
        {
            AccountManager oManager = new AccountManager();
            DataTable oTable = new DataTable();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            oTable = oManager.GetAccounts("Salesman");
            cboSalesman.Visible = false;    
            cboSalesman.Properties.DataSource = oTable;
            cboSalesman.Properties.DisplayMember = "AccountHolder";
            cboSalesman.Properties.ValueMember = "AcctCode";

            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("AcctCode", "AcctCode", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboSalesman.Properties.Columns.Add(col);

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("AccountHolder", "AccountHolder", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboSalesman.Properties.Columns.Add(col);

            cboSalesman.Refresh();
            cboSalesman.Visible = true;
            oManager.Close();

        }

        void RemoveBlankLastRowFirst()
        {
            int iCount = -1;
            gridViewSI.MoveLast();
            try
            {
                int[] oRow = gridViewSI.GetSelectedRows();

                iCount = oRow[0];
                string sItemCode = "";


                sItemCode = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridViewSI.DeleteRow(iCount);
                }
            }
            catch { }

        }

        void CancelOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to cancel this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                InvoiceManager oManager = new InvoiceManager();
                InvoiceUnit oUnit = new InvoiceUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                oUnit.DocumentCode = cboDocument.Text;
                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                
                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;
                
                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateInvoice(oUnit);
                oManager.Close();
                #endregion

                if (UpdateDataOnStatus == false)
                {
                    MainMenu oForm = (MainMenu)this.MdiParent;

                    oForm.ErrMsg.ImageIndex = 8;
                    oForm.ErrMsg.Caption = "Updating document is successfull!!!";
                    oForm.timer1.Enabled = true;
                    //MessageBox.Show("Updating document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    UpdateDataOnStatus = true;
                }
                #endregion

                oManager = new InvoiceManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CancelOrder(sDocNumber, this.ActiveUserID);
                oManager.Close();

                DeliveryManager DRManager = new DeliveryManager();

                DRManager.ConnectionString = this.ConnectionString;
                DRManager.Open();

                DRManager.PostDocument(txtReference.Text, this.ActiveUserID);

                DRManager.Close();

                txtStatus.Text = "Canceled";
            }

        }

        void ChangeToDeliverStatus(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to deliver this order?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                InvoiceManager oManager = new InvoiceManager();
                InvoiceUnit oUnit = new InvoiceUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                oUnit.DocumentCode = cboDocument.Text;

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;
                
                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateInvoice(oUnit);
                oManager.Close();
                #endregion

                if (UpdateDataOnStatus == false)
                {
                    MainMenu oForm = (MainMenu)this.MdiParent;

                    oForm.ErrMsg.ImageIndex = 8;
                    oForm.ErrMsg.Caption = "Updating document is successfull!!!";
                    oForm.timer1.Enabled = true;
                    //MessageBox.Show("Updating document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    UpdateDataOnStatus = true;
                }
                #endregion

                oManager = new InvoiceManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.DeliverOrder(cboLocation.EditValue.ToString(), txtReference.Text, sDocNumber, this.ActiveUserID);
                oManager.Close();

                txtStatus.Text = "Delivered";


            }
        }

        void ChangeToPostedStatus(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to post this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                InvoiceManager oManager = new InvoiceManager();
                InvoiceUnit oUnit = new InvoiceUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                oUnit.DocumentCode = cboDocument.Text;
                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;
                
                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateInvoice(oUnit);
                oManager.Close();
                #endregion

             
                #endregion

                oManager = new InvoiceManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.PostDocument(sDocNumber, this.ActiveUserID);
                oManager.Close();

                txtStatus.Text = "Posted";


                DeliveryManager oDRManager = new DeliveryManager();

                oDRManager.ConnectionString = this.ConnectionString;
                oDRManager.Open();

                oDRManager.CloseDR(txtReference.Text, this.ActiveUserID);
                oDRManager.Close();
            }
        }

        void ChangeToClosedStatus(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to close this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                InvoiceManager oManager = new InvoiceManager();
                InvoiceUnit oUnit = new InvoiceUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DocumentCode = cboDocument.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;
                
                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateInvoice(oUnit);
                oManager.Close();
                #endregion
                
                #endregion

                oManager = new InvoiceManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CloseOrder(sDocNumber, this.ActiveUserID);
                oManager.Close();

                txtStatus.Text = "Closed";

            }
        }

        public void ShowSearch()
        {
            FND_INVOICE oSearchDocument = new FND_INVOICE();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                InvoiceManager oManager = new InvoiceManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetInvoice(sDocumentNumber);


                #region Header
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                dtPostDate.EditValue = (DateTime)oRow["PostingDate"];
                dtDeliveryDate.EditValue = (DateTime)oRow["DueDate"];
                dtDocDate.EditValue = (DateTime)oRow["DocDate"];

                txtStoreCode.Text = oRow["StoreCode"].ToString();
                txtCardCode.EditValue = oRow["CardCode"].ToString();
                

                AddressBookManager oCardManager = new AddressBookManager();
                oCardManager.Connection = oManager.Connection;
                this.DefaultPriceList = oCardManager.GetPriceListCode(txtCardCode.Text);
                txtCardName.EditValue = oRow["CardName"].ToString();
                txtContactPerson.EditValue = oRow["ContactPerson"].ToString();
                txtPaymentTerms.Text = oRow["PaymentTerms"].ToString();

                txtReference.EditValue = oRow["Reference"].ToString();
                txtCustRefPO.EditValue = oRow["CustRefPO"].ToString();
                txtBillTo.EditValue = oRow["BillTo"].ToString();
                txtShipTo.EditValue = oRow["ShipTo"].ToString();
                cboSalesman.EditValue = oRow["SalesMan"].ToString();
                txtRemarks.EditValue = oRow["Remarks"].ToString();
                txtDivision.EditValue = oRow["Division"].ToString();
                cboDocument.EditValue = oRow["DocumentCode"].ToString();
                txtRefDoc.EditValue = oRow["DivReference"].ToString();
                cboLocation.EditValue = oRow["Location"].ToString();
                


                //if (oRow["Location"] != DBNull.Value)
                //{
                    
                //}
                if (oRow["VATCode"] != DBNull.Value)
                {
                    this.VATCode = oRow["VATCode"].ToString();
                }

                this.VATRate = oRow["VATRate"].ToString();

                if (oRow["IsVATInclusive"] != DBNull.Value)
                {

                    if (oRow["IsVATInclusive"].ToString() == "Y")
                    {
                        this.IsInclusive = true;
                    }
                    else
                    {
                        this.IsInclusive = false;
                    }
                }

                txtGrossAmount.EditValue = oRow["GrossAmount"].ToString();
                txtVAT.EditValue = oRow["VATAmount"].ToString();
                txtDisc1.EditValue = oRow["Discount1"].ToString();
                txtDisc2.EditValue = oRow["Discount2"].ToString();
                txtDisc3.EditValue = oRow["Discount3"].ToString();
                txtDisc4.EditValue = oRow["Discount4"].ToString();
                txtTotalDiscount.EditValue = oRow["TotalDiscount"].ToString();
                txtNetAmt.EditValue = oRow["NetAmount"].ToString();
                txtWithHoldingTax.Text = oRow["WithHoldingTax"].ToString();
                //oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                #endregion

                #region Line Items
                this.DeliveryLineItems = oManager.GetInvoiceLineItems(sDocumentNumber);
                gridControlSI.DataSource = this.DeliveryLineItems;
                gridControlSI.Refresh();


                #endregion

                #region Distributed Accounts
                this.AccountingEntries = oManager.GetAccountingDistribution(sDocumentNumber);

                gridInvAcctEntries.DataSource = this.AccountingEntries;
                gridInvAcctEntries.Refresh();

                #endregion


                if (txtStatus.Text == "Draft")
                {
                    if (gridViewSI.RowCount == 0)
                    {
                        gridViewSI.AddNewRow();
                    }
                }

                oManager.Close();

                btnAdd.Text = "Ok";
                GetBusinessPartnerDefaults(txtCardCode.Text);
                ComputeTotal();
                ApplyVolumeDiscount();
                txtDocumentNumber.Enabled = false;



            }

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(null, null);
            }
        }
        #endregion

        void BindUoM(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            UoMManager oManager = new UoMManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetUnitMeasures(sItemCode);

            oManager.Close();

            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["UoM"].ToString());
            }

        }

        #region Access Code


        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }


        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;
            btnCopyToSR.Enabled = false;

            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;
            btnCopyToSR.Enabled = true;
            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }


        #endregion

        private void SalesInvoice_Load(object sender, EventArgs e)
        {
            if (IsExportedFromDR == false)
            {
                BindWarehouse();
                BindCardDocument();
                cboLocation.EditValue = this.DefaultWarehouse;

                if (this.IsMultipleWarehouse == false)
                {
                    cboLocation.Enabled = false;
                }

                BindSalesMan();
                InitializeSeries();

                if (txtReference.Text != "")
                {
                    return;
                }

                dtPostDate.EditValue = System.DateTime.Now;
                dtDeliveryDate.EditValue = System.DateTime.Now;
                dtDocDate.EditValue = System.DateTime.Now;
                txtPaymentTerms.Text = "0";


                #region Binding Details
                if (this.DeliveryLineItems == null)
                {
                    this.DeliveryLineItems = GetTable();
                }

                gridControlSI.DataSource = this.DeliveryLineItems;
                gridControlSI.Refresh();

                if (gridViewSI.DataRowCount <= 0)
                {
                    gridViewSI.AddNewRow();
                }

                #endregion

                #region Binding Accounting G/L Entries
                if (this.AccountingEntries == null)
                {
                    this.AccountingEntries = GetGLAcctStructure();
                }

                gridInvAcctEntries.DataSource = this.AccountingEntries;
                gridInvAcctEntries.Refresh();

                if (gridViewInvAcctEntries.DataRowCount <= 0)
                {
                    gridViewInvAcctEntries.AddNewRow();
                }
                
                #endregion



            }
            
        }

        private void gridViewSI_KeyDown(object sender, KeyEventArgs e)
        {
            string _USR_AUTHORIZATION = ApplyAuthorization();
            try
            {
                string _ITEM_CODE = gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["ItemCode"]).ToString();
                BindLotNumber(_ITEM_CODE, cboLotNumber);
            }
            catch
            {
                //
            }
            if (_USR_AUTHORIZATION == "No Access" || _USR_AUTHORIZATION == "Read Only")
            {
                return;
            }

            try
            {
                int iCount = gridViewSI.FocusedRowHandle;

                if (e.KeyCode == Keys.Delete)
                {
                    if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (gridViewSI.IsLastRow)
                        {
                            string sItemCode = "";

                            iCount = gridViewSI.FocusedRowHandle;

                            sItemCode = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();
                            
                            if (sItemCode != "")
                            {
                                gridViewSI.DeleteRow(iCount);
                                gridViewSI.AddNewRow();
                            }
                        }
                        else
                        {
                            string sItemCode = "";

                            iCount = gridViewSI.FocusedRowHandle;
                            sItemCode = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();

                            if (sItemCode != "")
                            {
                                gridViewSI.DeleteRow(iCount);
                            }

                            gridViewSI.RefreshData();
                        }

                        ComputeTotal();
                        ApplyVolumeDiscount();
                    }
                }
                
                if (e.KeyCode == Keys.Down)
                {
                    if (gridViewSI.IsLastRow)
                    {
                        string sItemCode = "";
                        iCount = gridViewSI.FocusedRowHandle;

                        sItemCode = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();

                        if ((sItemCode != "" && (txtStatus.Text == "Draft" || txtStatus.Text == "Open")) && txtReference.Text == "")
                        {
                            gridViewSI.AddNewRow();

                            gridViewSI.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                            gridViewSI.FocusedColumn = gridViewSI.VisibleColumns[0];
                            gridViewSI.ShowEditor();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void btnSearchItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int iCount = gridViewSI.FocusedRowHandle;
            string _ItemGuID = System.Guid.NewGuid().ToString();
            

            FND_ITM_SO _FIND_ITEM_SO = new FND_ITM_SO();

            _FIND_ITEM_SO.ConnectionString = this.ConnectionString;
            _FIND_ITEM_SO.CustomerCode = this.txtCardCode.Text;

            foreach (DataRow oRows in this.DeliveryLineItems.Rows)
            {
                _FIND_ITEM_SO.ItemCodes.Add(oRows["ItemCode"].ToString());
            }

            _FIND_ITEM_SO.ShowDialog();

            if (_FIND_ITEM_SO.ItemCode != null)
            {
                if (_FIND_ITEM_SO.ItemCode.Trim() != "")
                {
                    UoMManager oUnitMeasureManager = new UoMManager();
                    oUnitMeasureManager.ConnectionString = this.ConnectionString;
                    oUnitMeasureManager.Open();


                    BindUoM(_FIND_ITEM_SO.ItemCode, cboUnitMeasure);

                    int _unitMeasureCount = 0;
                    double _PackSize = 1;
                    string _unitMeasure = "";

                    _unitMeasureCount = cboUnitMeasure.Items.Count;

                    if (_unitMeasureCount > 0)
                    {
                        _unitMeasure = _FIND_ITEM_SO.UOM;
                        _PackSize = oUnitMeasureManager.GetPackSize(_FIND_ITEM_SO.ItemCode, _unitMeasure);
                    }

                    oUnitMeasureManager.Close();

                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemCode"], _FIND_ITEM_SO.ItemCode);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemDesc"], _FIND_ITEM_SO.Description);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UoM"], _FIND_ITEM_SO.UOM);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"], _FIND_ITEM_SO.UnitPrice);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Qty"], 1);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["IsFree"], false);

                    
                    if (Convert.ToDouble(this.VATRate) == 0)
                    {
                        gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"], _FIND_ITEM_SO.UnitPrice);
                        
                    }
                    else
                    {

                        gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"], _FIND_ITEM_SO.UnitPrice);
                        
                    }

                    int _ZeroVAL = 0;

                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["CQty"], _PackSize);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["DiscPrcnt"], _ZeroVAL);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _ZeroVAL);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalDiscount"], _ZeroVAL);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemGuID"], _ItemGuID);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UoM"], _FIND_ITEM_SO.UOM);


                    #region Applying in Line Item Amount Computation
                    
                    double _UNITPRICE = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = 0 * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Discount"]).ToString());

                    double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _AMOUNT);
                    ComputeTotal();
                    ApplyVolumeDiscount();
                    #endregion

                    BindLotNumber(_FIND_ITEM_SO.ItemCode, cboLotNumber);
                }
                else
                {
                    gridViewSI.CancelUpdateCurrentRow();
                    if (gridViewSI.RowCount <= 0)
                    {
                        gridViewSI.AddNewRow();
                    }
                }
            }
            else
            {
                gridViewSI.CancelUpdateCurrentRow();
                if (gridViewSI.RowCount <= 0)
                {
                    gridViewSI.AddNewRow();
                }
            }

            _FIND_ITEM_SO.Dispose();
        }

        private void btnSearchItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            this.UsedKey = e.KeyCode;

            if (e.KeyCode == Keys.Enter)
            {
                #region New Code From Sales Order
                string _ItemGUID = System.Guid.NewGuid().ToString();

                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                try
                {
                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["UNITOFMEASURE"].ToString(),
                                        UnitPrice = row["UNITPRICE"].ToString()
                                    };


                        int iCount = -1;
                        int[] oRow = gridViewSI.GetSelectedRows();

                        iCount = oRow[0];

                        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
                        double _ZeroVAL = 0;
                        int iRowIndex = gridViewSI.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }

                        int iCountQty = 0;

                        try
                        {
                            iCountQty = Convert.ToInt32(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["Qty"]));
                        }
                        catch
                        {
                        }

                        foreach (var oUnit in items)
                        {
                            BindUoM(oUnit.ItemCode, cboUnitMeasure);
                            BindLotNumber(oUnit.ItemCode, cboLotNumber);
                            int _unitMeasureCount = 0;
                            double _PackSize = 0;
                            string _unitMeasure = "";
                            UoMManager oUnitMeasureManager = new UoMManager();
                            oUnitMeasureManager.ConnectionString = this.ConnectionString;
                            oUnitMeasureManager.Open();
                            _unitMeasureCount = cboUnitMeasure.Items.Count;

                            if (_unitMeasureCount > 0)
                            {
                                _unitMeasure = oUnit.UoM;
                                _PackSize = oUnitMeasureManager.GetPackSize(oUnit.ItemCode, _unitMeasure);
                            }

                            oUnitMeasureManager.Close();
                            gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemCode"], oUnit.ItemCode);
                            gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemDesc"], oUnit.Dscription);

                            gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["QtyOrder"], 0);
                            gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["CQtyOrder"], 0);

                            if (IsExportedFromDR == false || iCountQty == 0)
                            {
                                
                               
                    
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Qty"], 0);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["CQty"], _PackSize);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UoM"], oUnit.UoM);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"], oUnit.UnitPrice);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _ZeroVAL);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["DiscPrcnt"], _ZeroVAL);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _ZeroVAL);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _ZeroVAL);

                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemGuID"], _ItemGUID);
                            }
                        }
                        #endregion
                        try
                        {
                            string _ITEM_CODE = gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["ItemCode"]).ToString();

                            BindLotNumber(_ITEM_CODE, cboLotNumber);


                        }
                        catch
                        {
                            //
                        }

                        int iQtyServed = 0;
                        try
                        {
                            iQtyServed = Convert.ToInt16(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["Qty"]));
                        }
                        catch
                        {
                        }

                        int iCQtyServed = 0;
                        try
                        {
                            iCQtyServed = Convert.ToInt16(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["CQty"]));
                        }
                        catch
                        {
                        }

                        #region Applying in Line Item Amount Computation
                        double _UNITPRICE = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                        double _TOTAL_DISCOUNT = (iQtyServed * iCQtyServed) * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Discount"]).ToString());

                        double _AMOUNT = ((iQtyServed * iCQtyServed) * _UNITPRICE) - _TOTAL_DISCOUNT;
                        gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _AMOUNT);

                        ComputeTotal();
                        ApplyVolumeDiscount();
                        #endregion


                        gridViewSI.FocusedColumn = gridViewSI.Columns["Qty"];
                        SendKeys.Send("{ENTER}");
                        return;

                    }
                    else
                    {

                        if (!(this.UsedKey == Keys.Escape))
                        {


                            if (sItemCode.Trim() != "")
                            {
                                MessageBox.Show("No item found in the Price List!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                gridViewSI.FocusedColumn = gridViewSI.Columns["ItemCode"];

                                SendKeys.Send("{ENTER}");

                                return;
                            }
                            this.UsedKey = Keys.None;
                        }
                        else
                        {
                            this.UsedKey = Keys.None;
                        }
                    }
                }
                catch
                {
                }
                #endregion
            }


            if (e.KeyCode == Keys.Tab)
            {
                #region New Code From Sales Order
                string _ItemGUID = System.Guid.NewGuid().ToString();

                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                try
                {
                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["UNITOFMEASURE"].ToString(),
                                        UnitPrice = row["UNITPRICE"].ToString()
                                    };


                        int iCount = -1;
                        int[] oRow = gridViewSI.GetSelectedRows();

                        iCount = oRow[0];

                        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
                        double _ZeroVAL = 0;
                        int iRowIndex = gridViewSI.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }

                        int iCountQty = 0;

                        try
                        {
                            iCountQty = Convert.ToInt32(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["Qty"]));
                        }
                        catch
                        {
                        }

                        foreach (var oUnit in items)
                        {
                            BindUoM(oUnit.ItemCode, cboUnitMeasure);
                            gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemCode"], oUnit.ItemCode);
                            gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemDesc"], oUnit.Dscription);

                            if (IsExportedFromDR == false || iCountQty == 0)
                            {

                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Qty"], 0);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UoM"], oUnit.UoM);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"], oUnit.UnitPrice);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _ZeroVAL);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["DiscPrcnt"], _ZeroVAL);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _ZeroVAL);
                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _ZeroVAL);

                                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["ItemGuID"], _ItemGUID);
                            }
                        }
                        #endregion

                        int iQtyServed = 0;
                        try
                        {
                            iQtyServed = Convert.ToInt16(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["Qty"]));
                        }
                        catch
                        {
                        }

                        int iCQtyServed = 0;
                        try
                        {
                            iCQtyServed = Convert.ToInt16(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["CQty"]));
                        }
                        catch
                        {
                        }

                        #region Applying in Line Item Amount Computation
                        double _UNITPRICE = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                        double _TOTAL_DISCOUNT = (iQtyServed * iCQtyServed) * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Discount"]).ToString());

                        double _AMOUNT = ((iQtyServed * iCQtyServed) * _UNITPRICE) - _TOTAL_DISCOUNT;
                        gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _AMOUNT);

                        ComputeTotal();
                        ApplyVolumeDiscount();
                        #endregion


                        gridViewSI.FocusedColumn = gridViewSI.Columns["Qty"];
                        SendKeys.Send("{ENTER}");
                        return;

                    }
                    else
                    {

                        if (!(this.UsedKey == Keys.Escape))
                        {


                            if (sItemCode.Trim() != "")
                            {
                                MessageBox.Show("No item found in the Price List!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                gridViewSI.FocusedColumn = gridViewSI.Columns["ItemCode"];

                                SendKeys.Send("{ENTER}");

                                return;
                            }
                            this.UsedKey = Keys.None;
                        }
                        else
                        {
                            this.UsedKey = Keys.None;
                        }
                    }
                }
                catch
                {
                }
                #endregion
            }
            #region Disabled Code
            //if (e.KeyCode == Keys.Enter)
            //{
            //    try
            //    {
            //        DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;


            //        string sItemCode = oButtonEdit.Text;

            //        ItemManager oManager = new ItemManager();

            //        oManager.ConnectionString = this.ConnectionString;
            //        oManager.Open();

            //        DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

            //        oManager.Close();

            //        if (dt.Rows.Count > 0)
            //        {
            //            var items = from row in dt.AsEnumerable() 
            //                        select new
            //                        {
            //                            ItemCode = row["ItemCode"].ToString(),
            //                            Dscription = row["Description"].ToString(),
            //                            UoM = row["UNITOFMEASURE"].ToString(),
            //                            UnitPrice = row["UNITPRICE"].ToString()
            //                        };


            //            int iCount = -1;
            //            int[] oRow = gridView1.GetSelectedRows();

            //            iCount = oRow[0];

            //            string sVAT = this.VATCode.Trim() !="" ? this.VATCode : "N/A";

            //            foreach (var oUnit in items)
            //            {
            //                string _ItemGuID2 = System.Guid.NewGuid().ToString();
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], oUnit.UnitPrice);
            //                double _OrderQty = 0;
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["QtyOrder"], _OrderQty);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], false);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["GrossPrice"], oUnit.UnitPrice);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["NetPrice"], oUnit.UnitPrice);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], 0);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGuID2);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["VatCode"], sVAT);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["VatRate"], this.VATRate);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["VatApld"], 0);
            //            }
            //        }
            //    }
            //    catch
            //    {
            //    }
            //}
            #endregion
        }

        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                try
                {
                    int iCount = gridViewSI.FocusedRowHandle;

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    double _CQUANTITY = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());
                    string _ITEMCODE = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    //gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _AMOUNT);
                    bool IsChecked = false;
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["IsFree"], IsChecked);
                    ComputeTotal();
                    ApplyVolumeDiscount();
                }
                catch
                {
                }
            }
        }

        private void txtLineDiscount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = gridViewSI.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtLineDiscount = (DevExpress.XtraEditors.TextEdit)sender;

                double _lineDiscount = Convert.ToDouble(oTxtLineDiscount.Text);
                double _UnitPrice = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());
                double _Percentage = 0;

                _Percentage = _lineDiscount / _UnitPrice;

                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["DiscPrcnt"], (_Percentage * 100));
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], (_Qty * _CQty) * _lineDiscount);

                double _TotalDiscount = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"]).ToString());

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;
                
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _Amount);

                ComputeTotal();

            }
        }

        private void txtLineDiscPercent_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = gridViewSI.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtDiscPrcnt = (DevExpress.XtraEditors.TextEdit)sender;

                double _discPrcnt = Convert.ToDouble(oTxtDiscPrcnt.Text);
                double _UnitPrice = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());

                double _LineDiscount = _UnitPrice * (_discPrcnt/100);
                double _TotalDiscount = (_Qty *_CQty) * _LineDiscount;

                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _LineDiscount);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TotalDiscount);

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;
                
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _Amount);

                ComputeTotal();
                
            }
        }

        bool InComplete()
        {
            bool _Incomplete = false;

            if (txtDocumentNumber.Text == "") { return true; }
            if (txtCardCode.Text == "") { return true; }
            if (txtCardName.Text == "") { return true; }



            foreach (DataRow oRow in this.DeliveryLineItems.Rows)
            {
                if (oRow.RowState != DataRowState.Deleted)
                {
                    double _Qty = Convert.ToDouble(oRow["Qty"]);

                    if (_Qty == 0)
                    {
                        return true;
                    }
                }
            }

            return _Incomplete;

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            InvoiceManager oManager = new InvoiceManager();
            InvoiceUnit oUnit = new InvoiceUnit();


            if (txtRefDoc.Text == "")
            {
                MessageBox.Show("Please insert the predifined series of your document!!!", "Pre-Defined Series", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                bool IsExistingDRSIRef = oManager.IsReferenceSIDRNoExists(cboDocument.EditValue.ToString(), cboDocument.EditValue.ToString());

                oManager.Close();

                if (IsExistingDRSIRef == true)
                {
                    MessageBox.Show("Predifined series is already exists!!!", "Pre-Defined Series", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }


            if (cboLocation.EditValue == null)
            {
                MessageBox.Show("Please select warehouse!!!", "Warehouse", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            RemoveBlankLastRowFirst();
            
            if (InComplete() == false)
            {
                
                if (btnAdd.Text == "Add")
                {

                    #region Header - Sales Delivery

                    txtDocumentNumber.Text = GetNewSeries();
                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                    oUnit.StoreCode = txtStoreCode.Text;
                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.ContactPerson = txtContactPerson.Text;
                    oUnit.PaymentTerms = txtPaymentTerms.Text;

                    oUnit.Reference = txtReference.Text;
                    oUnit.CustRefPO = txtCustRefPO.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    oUnit.BillTo = txtBillTo.Text;
                    oUnit.Location = cboLocation.EditValue.ToString();

                    if (cboSalesman.EditValue != null)
                    {
                        oUnit.SalesMan = cboSalesman.EditValue.ToString();
                    }
                    else
                    {
                        oUnit.SalesMan = "";
                    }

                    oUnit.Remarks = txtRemarks.Text;

                    oUnit.TaxCode = this.VATCode.ToString();
                    oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                    if (oUnit.TaxCode != "NON-VAT")
                    {
                        oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                    }
                    else
                    {
                        oUnit.IsVATInclusive = "N/A";
                    }



                    oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                    oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                    oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                    oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                    oUnit.Discount1 = txtDisc1.Text;
                    oUnit.Discount2 = txtDisc2.Text;
                    oUnit.Discount3 = txtDisc3.Text;
                    oUnit.Discount4 = txtDisc4.Text;

                    oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                    oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                    oUnit.Division = txtDivision.Text;
                    oUnit.DocumentCode = cboDocument.Text;
                    oUnit.DivReference = txtRefDoc.Text;

                    oUnit.CreatedBy = this.ActiveUserID;
                    oUnit.ModifiedBy = this.ActiveUserID;

                    #endregion

                    oUnit.LineItems = this.DeliveryLineItems;
                    
                    

                    if (txtDocumentNumber.Text.Trim() != "")
                    {
                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        if (oManager.IsDocumentExists(txtDocumentNumber.Text) == false)
                        {
                            if (oManager.IsReferenceSIDRNoExists(cboDocument.EditValue.ToString(), txtRefDoc.Text) == false)
                            {
                                #region Adding Portion

                                System.Data.SqlClient.SqlException SqlEx = oManager.AddInvoice(oUnit);

                                if (SqlEx == null)
                                {
                                    txtDocumentNumber.Enabled = false;
                                    DeliveryManager _SALES_INVOICE_MANAGER = new DeliveryManager();

                                    _SALES_INVOICE_MANAGER.Connection = oManager.Connection;
                                    _SALES_INVOICE_MANAGER.SetDeliveryInProcess(txtReference.Text);


                                    btnAdd.Text = "Ok";
                                    MessageBox.Show("Adding document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                }
                                else
                                {
                                    MessageBox.Show(SqlEx.Message, "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                #endregion
                            }
                            else
                            {
                                MessageBox.Show("SI/DR Document reference is already exist in the record! Please try another document number then save it again!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                txtRefDoc.Focus();
                                txtRefDoc.SelectAll();
                            }
                                
                        }
                        else
                        {
                            MessageBox.Show("Document is already exist in the record! Please try another document number then save it again!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            txtDocumentNumber.Focus();
                            txtDocumentNumber.SelectAll();
                        }
                        oManager.Close();

                    }
                    else
                    {
                        MessageBox.Show("Please enter document number!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtDocumentNumber.Focus();
                        txtDocumentNumber.SelectAll();
                    }


                }
                else if (btnAdd.Text == "Update")
                {

                    #region Header Sales Delivery

                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                    oUnit.CustRefPO = txtCustRefPO.Text;
                    oUnit.StoreCode = txtStoreCode.Text;
                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.ContactPerson = txtContactPerson.Text;
                    oUnit.Reference = txtReference.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    oUnit.BillTo = txtBillTo.Text;
                    oUnit.Location = cboLocation.EditValue.ToString();

                    if (cboSalesman.EditValue != null)
                    {
                        oUnit.SalesMan = cboSalesman.EditValue.ToString();
                    }
                    else
                    {
                        oUnit.SalesMan = "";
                    }

                    oUnit.Remarks = txtRemarks.Text;

                    oUnit.TaxCode = this.VATCode.ToString();
                    oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                    if (oUnit.TaxCode != "NON-VAT")
                    {
                        oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                    }
                    else
                    {
                        oUnit.IsVATInclusive = "N/A";
                    }


                    oUnit.PaymentTerms = txtPaymentTerms.Text;
                    oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                    oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());

                    oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                    oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                    oUnit.Discount1 = txtDisc1.Text;
                    oUnit.Discount2 = txtDisc2.Text;
                    oUnit.Discount3 = txtDisc3.Text;
                    oUnit.Discount4 = txtDisc4.Text;

                    oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                    oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                    oUnit.Division = txtDivision.Text;
                    oUnit.DocumentCode = cboDocument.Text;
                    oUnit.DivReference = txtRefDoc.Text;

                    oUnit.ModifiedBy = this.ActiveUserID;
                    #endregion

                    oUnit.LineItems = this.DeliveryLineItems;
                    
                    #region Updating Portion
                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();
                    System.Data.SqlClient.SqlException SqlEx = oManager.UpdateInvoice(oUnit);
                    oManager.Close();
                    #endregion

                    if (SqlEx == null)
                    {
                        if (UpdateDataOnStatus == false)
                        {
                            MessageBox.Show("Updating document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            UpdateDataOnStatus = true;
                        }

                        btnAdd.Text = "Ok";
                    }
                    else
                    {
                        MessageBox.Show(SqlEx.Message.ToString(), "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    this.Close();
                }

            }
            else
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Please complete the required information, zero value in the quantity is also not allowed in the Line Items!!!";
                oForm.timer1.Enabled = true;
            }
        }

        private void txtDiscount_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc1.Text.Trim() != "0%" && txtDisc1.Text.Trim() != "" && txtDisc1.Text.Trim() != ".00%" && txtDisc1.Text.Trim() != "0" && txtDisc1.Text.Trim() != ".00")
            {
                txtDisc2.Enabled = true;
            }
            else
            {
                txtDisc2.Enabled = false;
                txtDisc2.Text = "0%";
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc2_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc2.Text.Trim() != "0%" && txtDisc2.Text.Trim() != "" && txtDisc2.Text.Trim() != ".00%" && txtDisc2.Text.Trim() != "0" && txtDisc2.Text.Trim() != ".00")
            {
                txtDisc3.Enabled = true;
            }
            else
            {
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc3_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".00%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".00")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc4_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".00%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".00")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDiscount_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc1.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc1.Text = string.Format("{0:###.00}", txtDisc1.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc1.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                txtDisc1.Text = "0%";
            }
        }

        private void txtDisc2_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc2.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc2.Text = string.Format("{0:###.00}", txtDisc2.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc2.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                txtDisc2.Text = "0%";
            }
        }

        private void txtDisc3_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc3.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc3.Text = string.Format("{0:###.00}", txtDisc3.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc3.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                txtDisc3.Text = "0%";
            }
        }

        private void txtDisc4_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc4.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc4.Text = string.Format("{0:###.00}", txtDisc4.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc4.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                txtDisc4.Text = "0%";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
            ApplyVolumeDiscount();

            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtDiscount_Enter(object sender, EventArgs e)
        {
            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
        }

        private void txtDisc2_Enter(object sender, EventArgs e)
        {
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
        }

        private void txtDisc3_Enter(object sender, EventArgs e)
        {
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
        }

        private void txtDisc4_Enter(object sender, EventArgs e)
        {
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");
        }

        private void txtDiscount_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc2_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc3_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc4_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }
        
        private void chkFree_CheckedChanged(object sender, EventArgs e)
        {
            int iCount = -1;
            int[] oRow = gridViewSI.GetSelectedRows();
            
            iCount = oRow[0];
            DevExpress.XtraEditors.CheckEdit oCheckBox = (DevExpress.XtraEditors.CheckEdit)sender;

            bool IsChecked = oCheckBox.Checked;
            int _ZeroVAL = 0;

            if (IsChecked == true)
            {
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["DiscPrcnt"], _ZeroVAL);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _ZeroVAL);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _ZeroVAL);
                
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _ZeroVAL);
            }
            else
            {
                string sItemCode = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();
                double dNetPrice = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                double iQty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Qty"]).ToString());
                double CQty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());
                
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["DiscPrcnt"], _ZeroVAL);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _ZeroVAL);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _ZeroVAL);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], (iQty * CQty) * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"])));
            }
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();
           

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = true;
                addRowToolStripMenuItem.Enabled = true;
                deleteRowToolStripMenuItem.Enabled = true;
                btnCopyToSR.Visible = false;
            }
            if (txtStatus.Text == "Canceled" || txtStatus.Text == "Closed")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
                btnCopyToSR.Visible = false;
            }

            if (txtStatus.Text == "Delivered")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();

                btnAdd.Enabled = true;
                btnAdd.Text = "Update";
                txtRefDoc.Enabled = true;

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;

                btnCopyToSR.Visible = true;
            }

            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;

                btnCopyToSR.Visible = true;
            }

            if (txtStatus.Text == "Open")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;

                btnCopyToSR.Visible = false;
            }
        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
           
            if (txtDocumentNumber.Text != "##########")
            {
                if (txtStatus.Text == "Draft" )
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                       
                        ChangeToPostedStatus(txtDocumentNumber.Text);
                           
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CancelOrder(txtDocumentNumber.Text);
                    }
                }
               
                else
                {

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        
                        ChangeToClosedStatus(txtDocumentNumber.Text);
                    }
                }
            }
            
        }

        private void txtReference_EditValueChanged(object sender, EventArgs e)
        {
            if (txtReference.Text.Trim() != "")
            {
                txtDisc1.Properties.ReadOnly = true;
                txtDisc2.Properties.ReadOnly = true;
                txtDisc3.Properties.ReadOnly = true;
                txtDisc4.Properties.ReadOnly = true;
                txtTotalDiscount.Properties.ReadOnly = true;
            }
            else
            {
                txtDisc1.Properties.ReadOnly = false;
                txtTotalDiscount.Properties.ReadOnly = false;
            }
        }

        private void dtPostDate_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }

            try
            {
                dtDeliveryDate.Properties.MinValue = (DateTime)dtPostDate.EditValue;
                dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));
            }
            catch { }
        }

        private void txtCardCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {

            

                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.SearchIndex = 0;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.ShowDialog();

                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
                txtBillTo.Text = _SearchBP.Address;
                txtContactPerson.Text = _SearchBP.ContactPerson;
                this.DefaultPriceList = _SearchBP.PriceList;
                this.VATCode = _SearchBP.VATCode;
                txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                txtDivision.Text = _SearchBP.Division;
                cboDocument.EditValue = _SearchBP.Document;
                this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                try
                {
                    cboDocument.Text = _SearchBP.Document;  //oRow["Documnt"].ToString();
                }
                catch
                {
                }

                try
                {
                    txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                    txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                    txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                    txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                }
                catch
                {
                }
                dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));
                //cboCurrency.Text 


                oTxManager.ConnectionString = this.ConnectionString;
                oTxManager.Open();


                this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

                if (this.VATCode != "NON-VAT")
                {
                    //lblVAT.Text = oTxManager.IsInclusive(this.VATCode) == "Y" ? "VAT:" : "VAT:";

                    lblVAT.Visible = true;
                    txtVAT.Visible = true;

                    lblTotalLineDiscount.Top = 426;
                    txtTotalLineDiscount.Top = 426;

                    lblDiscount.Top = 456;
                    txtDisc1.Top = 456;
                    txtDisc2.Top = 456;
                    txtDisc3.Top = 456;
                    txtDisc4.Top = 456;
                    txtTotalDiscount.Top = 456;

                    lblNetAmt.Top = 484;
                    txtNetAmt.Top = 484;


                }
                else
                {
                    lblVAT.Visible = false;
                    txtVAT.Visible = false;

                    lblTotalLineDiscount.Top = lblTotalLineDiscount.Top - 26;
                    txtTotalLineDiscount.Top = txtTotalLineDiscount.Top - 26;

                    lblDiscount.Top = lblDiscount.Top - 26;

                    txtDisc1.Top = txtDisc1.Top - 26;
                    txtDisc2.Top = txtDisc2.Top - 26;
                    txtDisc3.Top = txtDisc3.Top - 26;
                    txtDisc4.Top = txtDisc4.Top - 26;
                    txtTotalDiscount.Top = txtTotalDiscount.Top - 26;

                    lblNetAmt.Top = lblNetAmt.Top - 26;
                    txtNetAmt.Top = txtNetAmt.Top - 26;

                }

                oTxManager.Close();

                if (_SearchBP.BuyerSalesMan != "")
                {
                    cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                }

                _SearchBP.Dispose();
            }
            catch
            {
            }
        }

        private void txtCardCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByBPCode(txtCardCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByBPCode(txtCardCode.Text);

                            _SearchBP.ShowDialog();

                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                            this.VATCode = _SearchBP.VATCode;
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();

                    txtDivision.Text = oRow["Division"].ToString();
                    try
                    {
                        cboDocument.Text = oRow["Documnt"].ToString();
                    }
                    catch 
                    { 
                    }
                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void txtLineDiscPercent_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridViewSI.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtDiscPrcnt = (DevExpress.XtraEditors.TextEdit)sender;

                double _discPrcnt = Convert.ToDouble(oTxtDiscPrcnt.Text);
                double _UnitPrice = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());

                double _LineDiscount = _UnitPrice * (_discPrcnt / 100);
                double _TotalDiscount = (_Qty * _CQty) * _LineDiscount;

                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Discount"], _LineDiscount);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TotalDiscount);

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;

                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _Amount);

                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }
        }

        private void btnSearchItemCode_Leave(object sender, EventArgs e)
        {
            #region Old Code
            //string _ItemGUID = System.Guid.NewGuid().ToString();

            //DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

            //try
            //{
            //    string sItemCode = oButtonEdit.Text;
            //    ItemManager oManager = new ItemManager();

            //    oManager.ConnectionString = this.ConnectionString;
            //    oManager.Open();

            //    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

            //    oManager.Close();

            //    if (dt.Rows.Count > 0)
            //    {
            //        #region If Has Rows
            //        var items = from row in dt.AsEnumerable()
            //                    select new
            //                    {
            //                        ItemCode = row["ItemCode"].ToString(),
            //                        Dscription = row["Description"].ToString(),
            //                        UoM = row["UNITOFMEASURE"].ToString(),
            //                        UnitPrice = row["UNITPRICE"].ToString()
            //                    };


            //        int iCount = -1;
            //        int[] oRow = gridView1.GetSelectedRows();

            //        iCount = oRow[0];

            //        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
            //        double _ZeroVAL = 0;
            //        int iRowIndex = gridView1.FocusedRowHandle;

            //        if (iRowIndex < 0)
            //        {
            //            iRowIndex = 0;
            //        }
            //        foreach (var oUnit in items)
            //        {
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], oUnit.UnitPrice);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGUID);
            //        }
            //        #endregion


            //        #region Applying in Line Item Amount Computation
            //        double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
            //        double _TOTAL_DISCOUNT = 1 * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

            //        double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
            //        gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
            //        gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
            //        ComputeTotal();
            //        ApplyVolumeDiscount();
            //        #endregion
            //    }
            //    else
            //    {
            //        MessageBox.Show("No item found in the Price List!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        oButtonEdit.Text = "";
            //        oButtonEdit.Focus();
            //    }
            //}
            //catch
            //{
            //}
            #endregion

         
        }

        private void xtrInvoiceScrollable_Click(object sender, EventArgs e)
        {

        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")

                e.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void SalesInvoice_Shown(object sender, EventArgs e)
        {
            gridControlSI.Select();
            gridViewSI.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gridViewSI.FocusedColumn = gridViewSI.Columns["ItemCode"];
            gridViewSI.ShowEditor();

            

            txtCardCode.Focus();


            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }

        }

    

        private void cboUnitMeasure_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.ComboBoxEdit oCboUoM = (DevExpress.XtraEditors.ComboBoxEdit)sender;
            string sUoM = "";
            try
            {
                sUoM = Convert.ToString(oCboUoM.Text);
            }
            catch
            {
                sUoM = "";
            }
            if (sUoM != "")
            {
                gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["UoM"], sUoM);
            }
        }

        private void cboUnitMeasure_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sItemCode = "";
            string sUoM = "";

            int iFocusRowHandle = gridViewSI.FocusedRowHandle;

            try
            {
                sItemCode = gridViewSI.GetRowCellValue(iFocusRowHandle, gridViewSI.Columns["ItemCode"]).ToString();

                DevExpress.XtraEditors.ComboBoxEdit oCombo = (DevExpress.XtraEditors.ComboBoxEdit)sender;

                sUoM = oCombo.Text;

                UoMManager oManager = new UoMManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                double _PackSize = oManager.GetPackSize(sItemCode, sUoM);
                oManager.Close();

                gridViewSI.SetRowCellValue(iFocusRowHandle, gridViewSI.Columns["CQty"], _PackSize);



                int iCount = -1;
                int[] oRow = gridViewSI.GetSelectedRows();
                iCount = oRow[0];

                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                double _QUANTITY = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Qty"]).ToString());
                double _CQUANTITY = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());
                string _ITEMCODE = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();
                double _UNITPRICE = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Discount"]).ToString());

                double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _AMOUNT);
                bool IsChecked = false;
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["IsFree"], IsChecked);
                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }

        }

        private void cboSalesman_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

        private void SalesInvoice_Resize(object sender, EventArgs e)
        {
            if (this.Width > 863)
            {
                #region Upper Part Objects
                lblDocNo.Left = this.Width - 336;
                txtDocumentNumber.Left = this.Width - 173;

                lblDocStatus.Left = this.Width - 336;
                txtStatus.Left = this.Width - 173;

                lblPostDate.Left = this.Width - 336;
                dtPostDate.Left = this.Width - 173;

                lblValidUntilDeliveryDate.Left = this.Width - 336;
                dtDeliveryDate.Left = this.Width - 173;

                lblDocumentDate.Left = this.Width - 336;
                dtDocDate.Left = this.Width - 173;

                lblSeries.Left = this.Width - 336;
                cboDocument.Left = this.Width - 276;

                txtRefDoc.Left = this.Width - 173;
                #endregion

                gridControlSI.Width = this.Width - 56;


                #region Lower Part Objects
                lblGrossAmount.Left = this.Width - 443;
                txtGrossAmount.Left = this.Width - 336;

                lblTotalLineDiscount.Left = this.Width - 443;
                txtTotalLineDiscount.Left = this.Width - 336;

                lblDiscount.Left = this.Width - 443;
                txtDisc1.Left = this.Width - 336;
                txtDisc2.Left = this.Width - 284;
                txtDisc3.Left = this.Width - 229;
                txtDisc4.Left = this.Width - 174;
                txtTotalDiscount.Left = this.Width - 119;

                lblVAT.Left = this.Width - 443;
                txtVAT.Left = this.Width - 336;


                lblNetAmt.Left = this.Width - 443;
                txtNetAmt.Left = this.Width - 336;

                lblWithHoldingTax.Left = this.Width - 229;
                txtWithHoldingTax.Left = this.Width - 119;
                #endregion
            }
            else
            {

                lblDocNo.Left = 542;
                txtDocumentNumber.Left = 704;

                lblDocStatus.Left = 542;
                txtStatus.Left = 704;

                lblPostDate.Left = 542;
                dtPostDate.Left = 704;

                lblValidUntilDeliveryDate.Left = 542;
                dtDeliveryDate.Left = 704;

                lblDocumentDate.Left = 542;
                dtDocDate.Left = 704;

                lblSeries.Left = 542;
                cboDocument.Left = 601;

                txtRefDoc.Left = 704;

                gridControlSI.Width = 817;

                lblGrossAmount.Left = 434;
                lblTotalLineDiscount.Left = 434;

                txtGrossAmount.Left = 542;
                txtTotalLineDiscount.Left = 542;
                lblDiscount.Left = 434;
                txtDisc1.Left = 542;
                txtDisc2.Left = 594;
                txtDisc3.Left = 649;
                txtDisc4.Left = 704;
                txtTotalDiscount.Left = 759;

                lblVAT.Left = 434;
                txtVAT.Left = 542;

                lblNetAmt.Left = 434;
                txtNetAmt.Left = 542;

                lblWithHoldingTax.Left = 649;

                txtWithHoldingTax.Left = 759;

            }


            if (this.Height > 543)
            {
                gridControlSI.Height = this.Height - 359;

                lblSalesMan.Top = this.Height - 166;
                cboSalesman.Top = this.Height - 166;

                lblRemarks.Top = this.Height - 140;
                txtRemarks.Top = this.Height - 140;

                //btnCopyInvoice.Top = this.Height - 67;
                btnCopyToSR.Top = this.Height - 67;
                btnAdd.Top = this.Height - 67;
                btnCancel.Top = this.Height - 67;

                lblGrossAmount.Top = this.Height - 166;
                txtGrossAmount.Top = this.Height - 166;

                lblTotalLineDiscount.Top = this.Height - 139;
                txtTotalLineDiscount.Top = this.Height - 139;

                lblDiscount.Top = this.Height - 113;
                txtDisc1.Top = this.Height - 113;
                txtDisc2.Top = this.Height - 113;
                txtDisc3.Top = this.Height - 113;
                txtDisc4.Top = this.Height - 113;

                txtTotalDiscount.Top = this.Height - 113;
                lblVAT.Top = this.Height - 88;
                txtVAT.Top = this.Height - 88;

                lblNetAmt.Top = this.Height - 61;
                txtNetAmt.Top = this.Height - 61;


                lblWithHoldingTax.Top = this.Height - 85;
                txtWithHoldingTax.Top = this.Height - 85;


            }
            else
            {
                gridControlSI.Height = 184;

                lblSalesMan.Top = 377;
                cboSalesman.Top = 377;

                lblRemarks.Top = 403;
                txtRemarks.Top = 403;

                //btnCopyInvoice.Top = 476;
                btnCopyToSR.Top = 476;
                btnAdd.Top = 476;
                btnCancel.Top = 476;

                lblGrossAmount.Top = 377;
                txtGrossAmount.Top = 377;

                lblTotalLineDiscount.Top = 404;
                txtTotalLineDiscount.Top = 404;

                lblDiscount.Top = 430;
                txtDisc1.Top = 430;
                txtDisc2.Top = 430;
                txtDisc3.Top = 430;
                txtDisc4.Top = 430;
                txtTotalDiscount.Top = 430;

                lblVAT.Top = 455;
                txtVAT.Top = 455;

                lblNetAmt.Top = 482;
                txtNetAmt.Top = 482;


                lblWithHoldingTax.Top = 458;
                txtWithHoldingTax.Top = 458;
            }
        }

        private void gridControl1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                cntxtRightClickMenu.Show(Cursor.Position);
            }
        }

        private void addRowToolStripMenuItem_Click(object sender, EventArgs e)
        {


            if (gridViewSI.IsLastRow == false)
            {
                gridViewSI.MoveLast();
            }

            string _ItemCode = "";

            _ItemCode = gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["ItemCode"]).ToString();

            if (_ItemCode.Trim() == "")
            {
                MessageBox.Show("New row is already exists!!!", "Add Row", MessageBoxButtons.OK, MessageBoxIcon.Information);

                gridViewSI.MoveLast();
                gridViewSI.FocusedColumn = gridViewSI.Columns["ItemCode"];
                gridViewSI.ShowEditor();
            }
            else
            {
                gridViewSI.AddNewRow();

                txtCardCode.Focus();

                gridControlSI.Select();
                gridViewSI.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                gridViewSI.FocusedColumn = gridViewSI.VisibleColumns[1];
                gridViewSI.ShowEditor();
            }
        }

        private void insertNewRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iRowHandle = gridViewSI.FocusedRowHandle;

            DataTable dt = this.DeliveryLineItems;
            DataRow _BlankRow = dt.NewRow();

            dt.Rows.InsertAt(_BlankRow, iRowHandle);

            gridControlSI.DataSource = dt;
            gridControlSI.Refresh();

            gridViewSI.FocusedRowHandle = iRowHandle;
        }

        private void deleteRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iCount = gridViewSI.FocusedRowHandle;


            if (txtStatus.Text == "Draft")
            {
                if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {

                    if (gridViewSI.IsLastRow)
                    {
                        string sItemCode = "";


                        iCount = gridViewSI.FocusedRowHandle;
                        sItemCode = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();


                        if (sItemCode != "")
                        {
                            gridViewSI.DeleteRow(iCount);
                            gridViewSI.AddNewRow();
                        }


                        gridViewSI.RefreshData();

                    }
                    else
                    {


                        iCount = gridViewSI.FocusedRowHandle;

                        gridViewSI.DeleteRow(iCount);
                        gridViewSI.RefreshData();
                    }

                    ComputeTotal();
                }
            }
                 
        }

        private void copyToReturnMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void txtStoreCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {

          

                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.SearchIndex = 2;
                _SearchBP.ShowDialog();

                txtStoreCode.Text = _SearchBP.StoreCode;
                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
                txtBillTo.Text = _SearchBP.Address;
                txtContactPerson.Text = _SearchBP.ContactPerson;
                this.DefaultPriceList = _SearchBP.PriceList;
                this.VATCode = _SearchBP.VATCode;
                txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                txtDivision.Text = _SearchBP.Division;
                cboDocument.EditValue = _SearchBP.Document;


                try
                {
                    txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                    txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                    txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                    txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                }
                catch
                {
                }
                dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));
                //cboCurrency.Text 


                oTxManager.ConnectionString = this.ConnectionString;
                oTxManager.Open();


                this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

                if (this.VATCode != "NON-VAT")
                {
                    //lblVAT.Text = oTxManager.IsInclusive(this.VATCode) == "Y" ? "VAT:" : "VAT:";

                    lblVAT.Visible = true;
                    txtVAT.Visible = true;

                    lblTotalLineDiscount.Top = 426;
                    txtTotalLineDiscount.Top = 426;

                    lblDiscount.Top = 456;
                    txtDisc1.Top = 456;
                    txtDisc2.Top = 456;
                    txtDisc3.Top = 456;
                    txtDisc4.Top = 456;
                    txtTotalDiscount.Top = 456;

                    lblNetAmt.Top = 484;
                    txtNetAmt.Top = 484;


                }
                else
                {
                    lblVAT.Visible = false;
                    txtVAT.Visible = false;

                    lblTotalLineDiscount.Top = lblTotalLineDiscount.Top - 26;
                    txtTotalLineDiscount.Top = txtTotalLineDiscount.Top - 26;

                    lblDiscount.Top = lblDiscount.Top - 26;

                    txtDisc1.Top = txtDisc1.Top - 26;
                    txtDisc2.Top = txtDisc2.Top - 26;
                    txtDisc3.Top = txtDisc3.Top - 26;
                    txtDisc4.Top = txtDisc4.Top - 26;
                    txtTotalDiscount.Top = txtTotalDiscount.Top - 26;

                    lblNetAmt.Top = lblNetAmt.Top - 26;
                    txtNetAmt.Top = txtNetAmt.Top - 26;

                }

                oTxManager.Close();

                if (_SearchBP.BuyerSalesMan != "")
                {
                    cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                }

                _SearchBP.Dispose();
            }
            catch
            {
            }
        }

        private void txtStoreCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByStoreCode(txtStoreCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.SearchIndex = 2;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByStoreCode(txtStoreCode.Text);

                            _SearchBP.ShowDialog();

                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.VATCode = _SearchBP.VATCode;
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();

                    txtDivision.Text = oRow["Division"].ToString();
                    try
                    {
                        cboDocument.Text = oRow["Documnt"].ToString();
                    }
                    catch
                    {
                    }
                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void btnCopyToSR_Click(object sender, EventArgs e)
        {
            SalesReturn oForm = new SalesReturn();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ActiveUserID = this.ActiveUserID;
            oForm.DefaultWarehouse = this.DefaultWarehouse;
            oForm.IsMultipleWarehouse = this.IsMultipleWarehouse;

            oForm.ReferenceSINo = txtDocumentNumber.Text;
            oForm.MdiParent = this.MdiParent;
            oForm.CopyDeliveryToReturn(txtReference.Text);
            oForm.Show();
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {

        }

        private void distributionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InvoiceDistribution oForm = new InvoiceDistribution();

            oForm.ConnectionString = this.ConnectionString;
            oForm.DocumentNumber = txtDocumentNumber.Text;

            oForm.ShowDialog();
        }

        private void duplicateToolMenu_Click(object sender, EventArgs e)
        {
            EnableControls();
            InitializeSeries();
            btnAdd.Text = "Add";
            txtStatus.Text = "Draft";
            btnCopyToSR.Visible = false;
        }

        private void txtCardCode_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboLocation_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtCustRefPO_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtDivision_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtShipTo_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboDocument_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRefDoc_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboSalesman_EditValueChanged_1(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRemarks_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void dtDeliveryDate_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void dtDocDate_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtQty_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.TextEdit textQty = (DevExpress.XtraEditors.TextEdit)sender;
            double iQty = 0;
            try
            {
                iQty = Convert.ToDouble(textQty.Text);

                    int iCount = gridViewSI.FocusedRowHandle;

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    double _CQUANTITY = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());
                    string _ITEMCODE = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    //gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _AMOUNT);
                    bool IsChecked = false;
                    gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["IsFree"], IsChecked);
                    ComputeTotal();
                    ApplyVolumeDiscount();
                
            }
            catch
            {
                iQty = 0;
            }
            gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["QtyServed"], iQty);
        }

        private void cboLotNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            double iPackSize = 1;

            CNotebook.Inventory.UoMManager unitMeasureManager = new UoMManager();

            string _WarehouseCode = cboLocation.EditValue.ToString();
            string _ItemCode = gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["ItemCode"]).ToString();
            string _unitMeasure = gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["UoM"]).ToString();
            string _LotNumber = ((DevExpress.XtraEditors.ComboBoxEdit)sender).EditValue.ToString();

            unitMeasureManager.ConnectionString = this.ConnectionString;
            unitMeasureManager.Open();

            iPackSize = unitMeasureManager.GetPackSize(_ItemCode, _unitMeasure);

            unitMeasureManager.Close();

            gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["LotNumber"], _LotNumber);
            gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["CQty"], iPackSize);




            StockManager oManager = new StockManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            double _OrderQty = Convert.ToDouble(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["QtyOrder"]));
            double _OnStockQty = oManager.GetAvailableQuantity(_WarehouseCode, _ItemCode, _LotNumber);
            double _UnitCost = oManager.GetUnitCost(_WarehouseCode, _ItemCode, _LotNumber);


            gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["Qty"], _OnStockQty);
            gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["UnitCost"], _UnitCost);

            gridViewSI.FocusedColumn = gridViewSI.Columns["Qty"];
            gridViewSI.ShowEditor();

            oManager.Close();
        }

        private void gridViewSI_FocusedColumnChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs e)
        {
            if (e.FocusedColumn == gridViewSI.Columns["LotNumber"])
            {
                BindLotNumber(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["ItemCode"]).ToString(), cboLotNumber);
            }
        }

        private void gridViewSI_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridViewSI.FocusedColumn == gridViewSI.Columns["LotNumber"])
            {
                BindLotNumber(gridViewSI.GetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["ItemCode"]).ToString(), cboLotNumber);
            }
        }

        private void txtQty_DragOver(object sender, DragEventArgs e)
        {

        }

        private void txtQty_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            DevExpress.XtraEditors.TextEdit textQty = (DevExpress.XtraEditors.TextEdit)sender;
            double iQty = 0;
            try
            {
                iQty = Convert.ToDouble(e.NewValue);
            }
            catch
            {
                iQty = 0;
            }
            gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["QtyServed"], iQty);
        }

        private void ribbonCtlAR_Click(object sender, EventArgs e)
        {

        }

        private void barReversal_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void txtQty_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCount = gridViewSI.FocusedRowHandle;

                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                double _CQUANTITY = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["CQty"]).ToString());
                string _ITEMCODE = gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["ItemCode"]).ToString();
                double _UNITPRICE = Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["UnitPrice"]).ToString());
                double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewSI.GetRowCellValue(iCount, gridViewSI.Columns["Discount"]).ToString());

                double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                //gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["Amount"], _AMOUNT);
                bool IsChecked = false;
                gridViewSI.SetRowCellValue(iCount, gridViewSI.Columns["IsFree"], IsChecked);
                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }

            gridViewSI.SetRowCellValue(gridViewSI.FocusedRowHandle, gridViewSI.Columns["Qty"], ((DevExpress.XtraEditors.TextEdit)sender).Text);
        }

        private void txtAcctCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_GLACCOUNT oForm = new FND_GLACCOUNT();

            oForm.ConnectionString = this.ConnectionString;

            oForm.ShowDialog();

            gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"], oForm.SelectedGLAcctCode);
            gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctName"], oForm.SelectedGLAcctName);

        }

        private void barSaveARDistribution_ItemClick(object sender, ItemClickEventArgs e)
        {
            InvoiceManager oManager = new InvoiceManager();

            RemoveBlankLastGLAccounts();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            SqlException ex = oManager.AddDistributionEntries(this.txtDocumentNumber.Text, this.AccountingEntries);

            if (ex != null)
            {
                MessageBox.Show(ex.Message.ToString(), "Error Saving", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Accounting is successfully saved!!!", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            oManager.Close();
        }

        private void barClear_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.AccountingEntries = GetGLAcctStructure();

            gridInvAcctEntries.DataSource = this.AccountingEntries;
            gridInvAcctEntries.Refresh();
        }

        private void barPostEntries_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void gridViewInvAcctEntries_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (gridViewInvAcctEntries.GetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"]).ToString() != "")
                {
                    if (MessageBox.Show("Are you sure you want to delete this item?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        gridViewInvAcctEntries.DeleteRow(gridViewInvAcctEntries.FocusedRowHandle);
                    }
                }
            }
            if (e.KeyCode == Keys.Down)
            {
                int iRowIndex = gridViewInvAcctEntries.FocusedRowHandle;
                if (gridViewInvAcctEntries.RowCount <= 0)
                {
                    gridViewInvAcctEntries.AddNewRow();
                    return;
                }
                gridViewInvAcctEntries.FocusedRowHandle = iRowIndex;
                if (gridViewInvAcctEntries.GetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"]).ToString() != "")
                {
                    gridViewInvAcctEntries.AddNewRow();
                }
            }
        }

        private void barNewEntry_ItemClick(object sender, ItemClickEventArgs e)
        {
            int iRowIndex = gridViewInvAcctEntries.RowCount;
            if (gridViewInvAcctEntries.RowCount <= 0)
            {
                gridViewInvAcctEntries.AddNewRow();
                return;
            }

            gridViewInvAcctEntries.FocusedRowHandle = iRowIndex - 1;
            try
            {
                string _AcctCode = "";


                if (gridViewInvAcctEntries.GetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"]) != null)
                {
                    _AcctCode = gridViewInvAcctEntries.GetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"]).ToString();
                }
                else
                {
                    _AcctCode = "";
                }

                if (_AcctCode.Trim() == "")
                {
                    return;
                }
            }
            catch { }


            gridViewInvAcctEntries.AddNewRow();
        }

        private void txtAcctCode_ButtonClick_1(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_GLACCOUNT oForm = new FND_GLACCOUNT();

            oForm.ConnectionString = this.ConnectionString;

            oForm.ShowDialog();

            gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"], oForm.SelectedGLAcctCode);
            gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctName"], oForm.SelectedGLAcctName);
        }

        private void txtAcctCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_ACCOUNTCODE = (DevExpress.XtraEditors.TextEdit)sender;

                ChartOfAccountManager oManager = new ChartOfAccountManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable dt = oManager.GetChartOfAccountByAcctCode(_TEXT_ACCOUNTCODE.Text);
                oManager.Close();


                if (dt.Rows.Count > 0)
                {
                    DataRow oRow = dt.Rows[0];

                    string sAcctCode = oRow["AcctCode"].ToString();
                    string sAcctName = oRow["AcctName"].ToString();
                    gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"], sAcctCode);
                    gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctName"], sAcctName);


                }

                else
                {

                    FND_GLACCOUNT oForm = new FND_GLACCOUNT();

                    DevExpress.XtraEditors.TextEdit eGLAccount = (DevExpress.XtraEditors.TextEdit)sender;

                    oForm.ConnectionString = this.ConnectionString;
                    oForm.SetSearch(eGLAccount.Text);
                    oForm.ShowDialog();

                    gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctCode"], oForm.SelectedGLAcctCode);
                    gridViewInvAcctEntries.SetRowCellValue(gridViewInvAcctEntries.FocusedRowHandle, gridViewInvAcctEntries.Columns["AcctName"], oForm.SelectedGLAcctName);

                }
                //grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.Columns["Particulars"];

            }
        }

        private void txtReference_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_REFERENCE_DR oForm = new FND_REFERENCE_DR();
            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();
        }
        
    }
}
